package com.smh.yunpicturebackend.aop;

import com.smh.yunpicturebackend.annotation.AuthCheck;
import com.smh.yunpicturebackend.exception.BusinessException;
import com.smh.yunpicturebackend.exception.ErrorCode;
import com.smh.yunpicturebackend.pojo.constant.UserConstant;
import com.smh.yunpicturebackend.pojo.domain.User;
import com.smh.yunpicturebackend.pojo.enums.UserRoleEnum;
import com.smh.yunpicturebackend.utils.ResultUtils;
import com.smh.yunpicturebackend.utils.UserThreadLocal;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * @author shiminghui
 * @date 2025/6/15 15:11
 * @description: 权限校验AOP类
 */
@Component
@Aspect
public class AuthInterceptor {

    /**
     * 权限校验
     *
     * @param joinPoint 连接点
     * @param authCheck 注解
     * @return 执行结果
     * @throws Throwable
     */
    @Around("@annotation(authCheck)") // @annotation(authCheck) 表示拦截带有 @AuthCheck 注解的方法
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        User user = UserThreadLocal.get();
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        String mustRole = authCheck.mustRole();
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        if (mustRoleEnum == null) { // 没有指定必须的角色
            return joinPoint.proceed();
        }

        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(user.getUserRole());

        // 判断是否为管理员
        if (UserRoleEnum.ADMIN == mustRoleEnum && UserRoleEnum.ADMIN != userRoleEnum) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        return joinPoint.proceed();
    }

}
